/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-07-24 16:02:56
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-08-07 22:00:00
 * @FilePath: /yyshort/lib/pages/home/controller.dart
 * @Description: 基于connectivity_plus的网络检测实现
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yyshort/common/apis/home_api.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/apis/video_api.dart';
import 'package:yyshort/common/model/useInfo_model.dart';
import 'package:yyshort/common/model/user.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/common/store/config.dart';
import 'package:yyshort/common/store/user.dart';
import 'package:yyshort/common/utils/network_provider.dart';
import 'package:yyshort/pages/ali_player/short_video/SharedDataController.dart';

import 'index.dart';

class HomeController extends GetxController {
  HomeController();

  final state = HomeState();
  // 网络状态相关变量
  final RxBool issConnected = true.obs;
  // bool get isConnected => _isConnected.value;

  /// UI 组件
  final RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  int curPage = 1;
  int total = 20;
  UserInfo userinfo = UserInfo();
  late final ScrollController scrollController = ScrollController();

  // 获取banner数据
  Future<void> bannerData() async {
    await HomeAPI.home_banner().then((value) {
      state.bannerList.assignAll(value);
    });
  }

  // 获取推荐数据
  Future<void> recommendData() async {
    final value = await HomeAPI.home_recommend();
    state.recommendlist.assignAll(value);
  }

  Future<void> onRefresh() async {
    //异步并发
    await Future.wait([
      bannerData(),
      recommendData(),
      VideoAPI.for_you_videos(),
    ]);

    fetchNewsList(isRefresh: true)
        .then((_) {
          if (state.trendingList.length < total * curPage) {
            refreshController.loadNoData();
            refreshController.refreshCompleted(resetFooterState: true);
          } else {
            refreshController.refreshCompleted(resetFooterState: true);
          }
        })
        .catchError((_) {
          refreshController.refreshFailed();
        });
  }

  Future<void> onLoading() async {
    await fetchNewsList()
        .then((_) {
          if (state.trendingList.length < total * curPage) {
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        })
        .catchError((_) {
          refreshController.loadFailed();
        });
  }

  Future<void> fetchNewsList({bool isRefresh = false}) async {
    if (isRefresh == true) {
      curPage = 1;
    } else {
      curPage++;
    }
    List<VideoModel> result = await HomeAPI.home_waterfall(
      page: (curPage).toString(),
    );
    if (isRefresh == true) {
      state.trendingList.clear();
    }
    state.trendingList.addAll(result);
  }

  /// 初始化
  @override
  Future<void> onInit() async {
    super.onInit();

    eventBus.on<NetWorkRefreshEvent>().listen((event) {
      coustomInit();
    });

    // 监听滚动位置并保存
    scrollController.addListener(() {
      state.scrollPosition = scrollController.offset;
    });
  }

  Future<void> coustomInit() async {
    if (userinfo.token == '') {
      await UserAPI.guestLogin().then((token) async {});
      await UserAPI.get_user_info().then((token) async {
        onRefresh();
      });
    } else {
      await UserAPI.get_user_info().then((token) async {
        onRefresh();
      });
    }
  }

  /// 页面就绪时加载数据
  @override
  Future<void> onReady() async {
    super.onReady();
    bool isConnected = Get.find<NetworkService>().isConnected;
    if (isConnected) {
      await coustomInit();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (state.scrollPosition > 0) {
          final scrollController = this.scrollController;
          scrollController.jumpTo(state.scrollPosition);
        }
      });
    }
  }

  /// 清理资源
  @override
  void onClose() {
    super.onClose();
  }
}
